/**
 * Created by li Hong 2017/10/10 0025.
 */
//用户管理
var role = null;
$(function () {
    var table = new tableFactory();
    addListeners(table);
});

function tableFactory() {
    var me = this;
    me.data = null;
    me.maxId = 0;
    me.enabled = null;
    me.userRoleData = null;
    me.roleData = null;
    me.deptData = null;
    var init = function () {
        $.when(loadDeptData(me)).then(function () {
            $("#user").bootstrapTable({
                method: 'get',					  //请求方式（*）
                striped: true,					  //是否显示行间隔色
                cache: false,					   //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
                pagination: true,				   //是否显示分页（*）
                sortable: true,					 //是否启用排序
                sortOrder: "asc",				   //排序方式
                sidePagination: "client",		   //分页方式：client客户端分页，server服务端分页（*）
                pageNumber: 1,					   //初始化加载第一页，默认第一页
                search: true,					   //是否显示表格搜索，只能进行客户端搜索
                strictSearch: false,                //true为全匹配，false为模糊查询
                showColumns: true,				  //是否显示筛选列按钮
                showRefresh: false,				  //是否显示刷新按钮
                clickToSelect: true,				//是否启用点击选中行
                showToggle: false,					//是否显示详细视图和列表视图的切换按钮
                cardView: false,					//是否显示详细视图
                detailView: false,				   //是否显示父子表
                singleSelect: false,               //表示支持多选，false表示支持，true表示不支持
                height: 'auto',
                pageSize: 10,
                pageList: [5,10,20],
                columns: [{
                    title:'序号',
                    field: 'check',
                    checkbox: true,
                    align: 'center',
                    valign: 'middle'
                }, {
                    title: '所属部门', field: 'deptname', align: 'center',
                    formatter: function (value, row, index) {
                        return me.getDeptName(row.departmentid);
                    }
                }, {
                    title: '登录账号', field: 'loginname', align: 'center'
                }, {
                    title: '真实姓名', field: 'realname', align: 'center'
                }, /*{
                    title: '登录密码', field: 'loginpassword', align: 'center'
                }, */{
                    title: '电话', field: 'phone', align: 'center'
                }, {
                    title: '头衔', field: 'title', align: 'center'
                }, {
                    title: '性别', field: 'sex', align: 'center',
                    formatter: function (value) {
                        return value == 1 ? '男' : (value == 0 ? '女' : '');
                    }
                }, {
                    title: 'QQ', field: 'qq', align: 'center'
                }, {
                    title: '序号', field: 'ordernum', align: 'center'
                }, /*{
                    title: '微信ID', field: 'weixinid', align: 'center'
                }, {
                    title: '微信名称', field: 'weixinname', align: 'center'
                }, {
                    title: '备注', field: 'remark', align: 'center'
                },*/{
                    title: '角色', field: 'rolename', align: 'center',
                    formatter: function (value, row, index) {
                        var roleids = me.getUserRoleByUserId(row.userid);
                        return  me.getRoleByRoleId(roleids);
                    }
                } /*{
                    title: '操作',
                    field: '',
                    width: '20%',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var html = [];
                        html.push('<button class="btn btn-warning btn-xs" style="margin: 0px 5px;">修改</button>');
                        html.push('<button class="btn btn-danger btn-xs" style="margin: 0px 5px;">删除</button>');
                        return html.join('');
                    },
                    events: {
                        'click .btn-warning': function (e, value, row, index) {
                            me.update(row);
                        },
                        'click .btn-danger': function (e, value, row, index) {
                            me.delete();
                        }
                    }
                }*/]
            });
            me.loadData();
        });
    };
    init();
}

tableFactory.prototype = {
    //获取用户数据
    loadData: function () {
        var me = this;
        $.when(me.loadRoleData()).then(function () {
            $.getJSON('../userManage/selectAll', '', function (_data) {
                me.data = _data;
                $("#user").bootstrapTable("load", _data);
            });
        });
    },
    //获取角色表数据
    loadRoleData: function () {
        var def = $.Deferred();
        var me = this;
        $.when(me.loadUserRoleData()).then(function () {
            $.getJSON('../roleManage/selectAll', '', function (_data) {
            me.roleData = _data;
            def.resolve();
        });
         });
        return def.promise();
    },
   //加载用户角色数据
    loadUserRoleData: function () {
        var def = $.Deferred();
        var me = this;
       // $.when(me.loadRoleData()).then(function () {
        $.getJSON('../userRoleManage/selectAll', '', function (_data) {
            me.userRoleData = _data;
            def.resolve();
        });
       // });
        return def.promise();
    },
    //获取用户角色表中角色ID,传进来的是用户ID
    getUserRoleByUserId: function (userId) {
        var roleId;
        var me = this;
        $.each(me.userRoleData, function (index, item) {
            //alert(item.userId);
            //alert(typeof item.userId);
            if (item.userId === userId) {
                roleId = item.roleId;
                return false;
            }
        });
        return roleId;
    },
    //根据角色Id得到角色名称
    getRoleByRoleId: function (roleId) {
        var roleName = '';
        var me = this;
        $.each(me.roleData, function (index, item) {
            if (item.roleid === roleId) {
                roleName = item.rolename;
                return false;
            }
        });
        return roleName;
    },
    //得到部门名称
    getDeptName: function (id) {
        var name = '';
        $.each(this.deptData, function (index, item) {
            if (item.departmentid === id) {
                name = item.deptname;
                return false;
            }
        });
        return name;
    },

    save: function () {
        var me = this;
        var html = [];
        html.push('<div style="margin: 10px;"><table class="table table-bordered table-normal">');
        html.push('<tr><td>用户名：</td><td><input type="text" class="form-control" id="new-username" /></td></tr>');
        html.push('<tr><td>密码：</td><td><input type="text" class="form-control" id="new-password" /></td></tr>');
        html.push('<tr><td>真实姓名：</td><td><input type="text" class="form-control" id="new-realname" /></td></tr>');
        html.push('<tr><td>部门：</td><td><select type="text" class="form-control" id="new-departmentid">');
        html.push('<option value="">无</option>');
        $.each(me.deptData, function (index, item) {
            html.push('<option value="' + item.departmentid + '">' + item.deptname + '</option>');
        });
        html.push('</select></td></tr>');
        html.push('</table></div>');

        layer.open({
            type: 1, area: '500px', title: '添加用户', btn: ['确定'],
            content: html.join(''),
            yes: function (index) {
                var p = {
                    loginname: $("#new-username").val(),
                    loginpassword: $("#new-password").val(),
                    realname: $("#new-realname").val(),
                    departmentid: $("#new-departmentid").val()
                };
                console.log(p);
                layer.close(index);
                $.post("../userManage/insert", p, function (data) {
                    if (data === true) {
                        me.loadData();
                        layer.msg("添加成功！", {icon: 1});
                    } else {
                        layer.msg("添加失败！", {icon: 2});
                    }
                })
            }
        });
    },
    delete: function () {
        var me = this;
        var selects = $('#user').bootstrapTable("getSelections");
        if (selects.length > 0) {
            layer.confirm('确定删除?', {icon: 3, title:'提示'}, function (index) {
                var deletes = [];
                $.each(selects, function (index, item) {
                    deletes.push({
                        userid:item.userid
                    });
                });
                $.ajax({
                    url: '../userManage/delete',
                    type: 'POST',
                    contentType : 'application/json;charset=utf-8', //设置请求头信息
                    dataType: 'json',
                    data: JSON.stringify(deletes),
                    success: function (_data) {
                        if (_data > 0) {
                            me.loadData();
                            layer.msg("已删除"+_data+"条数据！", {icon: 1});
                        }
                    }
                });
                layer.close(index);
            });
        } else {
            layer.msg("请选择要删除的部门！", {icon: 0});
        }
    },
    edit: function () {
        var me = this;
        var selects = $('#user').bootstrapTable("getSelections");
        var len = selects.length;
        if (len === 1) {
            var editItem = selects[0];
            var html = [];
            html.push('<div style="margin: 10px;"><table class="table table-bordered table-normal">');
            html.push('<tr><td>用户名：</td><td><input type="text" class="form-control" id="edit-username" /></td></tr>');
            html.push('<tr><td>密码：</td><td><input type="text" class="form-control" id="edit-password" /></td></tr>');
            html.push('<tr><td>真实姓名：</td><td><input type="text" class="form-control" id="edit-realname" /></td></tr>');
            html.push('<tr><td>上级部门：</td><td><select type="text" class="form-control" id="edit-departmentid">');
            html.push('<option value="">无</option>');
            $.each(me.deptData, function (index, item) {
                html.push('<option value="' + item.departmentid + '">' + item.deptname + '</option>');
            });
            html.push('</select></td></tr>');
            html.push('</table></div>');

            layer.open({
                type: 1, area: '500px', title: '修改部门', btn: ['确定'],
                content: html.join(''),
                success: function () {
                    $('#edit-username').val(editItem.loginname);
                    $('#edit-password').val(editItem.loginpassword);
                    $('#edit-realname').val(editItem.realname);
                },
                yes: function (index) {
                    var p = {
                        userid:editItem.userid,
                        loginname: $("#edit-username").val(),
                        loginpassword: $("#edit-password").val(),
                        realname: $("#edit-realname").val(),
                        departmentid: $("#edit-departmentid").val()
                    };
                    layer.close(index);
                    $.post("../userManage/update", p, function (data) {
                        if (data === true) {
                            me.loadData();
                            layer.msg("修改成功！", {icon: 1});
                        } else {
                            layer.msg("修改失败！", {icon: 2});
                        }
                    })
                }
            });
        } else if (len > 1){
            layer.msg("只能选择一个部门！", {icon: 0});
        } else if (len === 0) {
            layer.msg("请选择要修改的部门！", {icon: 0});
        }
    },
    //修改
    update:function (data) {
        var html = [];
        var me = this;
        var Deptname = null;
        var id = data["departmentid"];//获取部门ID
        Deptname = me.getDeptName(id);//获取当前部门

        var roleId = me.getUserRoleByUserId(data.userid);//根据用户ID得到角色ID。
        var present = me.getRoleByRoleId(roleId);
        html.push('<div id="newRole">' +'<input type="hidden" id="edit_userid" value="'+data.userid+'">'+
            '<table class="sitetable table table-bordered">');
        html.push('<tr><td>登录用户：</td><td><input type="text" class="form-control" id="edit_loginName" validateVal="0" readonly="readonly"/></td></tr>');
        html.push('<tr><td>单位部门：</td><td><input type="text" class="form-control" id="edit_dept" validateVal="0"  readonly="readonly"/></td></tr>');
        html.push('<tr><td>拥有权限：</td><td><select class="form-control" id="edit_permission">');
        $.each(me.roleData, function (index, item) {
            if(item.rolename==present){
                html.push('<option value="' + roleId+ '" selected>' + present + '</option>');
            }else if(present==""){
                html.push('<option value="'+item.roleid+'">' + item.rolename + '</option>');
            }else{
                html.push('<option value="'+item.roleid+'">' + item.rolename + '</option>');
            }
        });
        html.push('</select></td></tr>');
        html.push('</table></div>');

        layer.open({
            type: 1,
            title: '分配权限',
            btn: ['OK'],//可以无限个按钮
            content: html.join(''),
            success: function (layero, index) {

                $("#edit_dept").val(Deptname);
                $("#edit_loginName").val(data["loginname"]);

            },
            yes:function (index) {
                me.getRoleByRoleId(data.userid)
                var p = {};
                p.userId = $("#edit_userid").val();
                p.roleId = $("#edit_permission").val();
                console.log(p)
                layer.close(index);
                $.post("../userRoleManage/insert",p,function (data) {
                    if (data === true) {
                        //loadRoleData();
                        /*addListeners(new tableFactory());*/

                        layer.msg("修改成功！", {icon: 1});
                        location.reload(true);
                    } else {
                        layer.msg("修改失败！", {icon: 2});
                    }
                });
            }
        });
    }

};
//加载部门数据
function loadDeptData (_this) {
    var def = $.Deferred();
    $.getJSON('../departmentManage/selectAll', '', function (_data) {
        _this.deptData = _data;
        //Deptcom = _data;
        def.resolve();
    });
     return def.promise();
}

function addListeners (tableObj) {
    $('#btn-add').off('click');
    $('#btn-delete').off('click');
    $('#btn-edit').off('click');
    $('#btn-add').on('click', function () {
        tableObj.save();
    });
    $('#btn-delete').on('click', function () {
        tableObj.delete();
    });
    $('#btn-edit').on('click', function () {
        tableObj.edit();
    });
}
